package com.woniuxy.rbac.shiro;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.woniuxy.rbac.entity.ResponseResult;
import com.woniuxy.rbac.utils.Audience;
import com.woniuxy.rbac.utils.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Auther: 老谭（<a href="http://www.woniuxy.com">蜗牛学苑</a>）
 */
@Slf4j
public class JwtFilter implements Filter {
//    @Autowired
//    private Audience audience;
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        log.debug("AuthFilter doFilter");
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;
        //判断是否访问的是登录
        String url = req.getRequestURL().toString();
        String uri = req.getRequestURI();
        log.debug("url:{},uri:{}", url, uri);
        //不是访问的登录接口,判断是否已认证（判断是否带有合法有效的jwt）
        String jwt = req.getHeader("token");
        if (jwt == null) { //没有带jwt
            ResponseResult result = new ResponseResult<>(403, "no login");
            ObjectMapper objectMapper = new ObjectMapper();
            resp.getWriter().print(objectMapper.writeValueAsString(result));
            resp.getWriter().close();
        } else {
            //Web环境中使用Spring提供的API获取Spring容器，再提供其getBean（）
            WebApplicationContext ctx= WebApplicationContextUtils.getWebApplicationContext(request.getServletContext());
            Audience audience=ctx.getBean(Audience.class);
            JwtUtil.verifyJwt(jwt,audience);
            chain.doFilter(request, response);
        }
    }
}
